package com.example.administrator.tianqi;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by Administrator on 2017/3/9.
 */

public class HttUtil {
    public static HttpClient httpClient = new DefaultHttpClient();

    /**
     *
     * @param url
     *            请求地址
     * @return 服务器响应的字符串
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static String getRequest(final String url)
            throws InterruptedException, ExecutionException {
        FutureTask<String> task = new FutureTask<String>(
                new Callable<String>() {

                    @Override
                    public String call() throws Exception {
                        // 创建HttpGet对象
                        HttpGet get = new HttpGet(url);
                        // 发送get请求
                        HttpResponse httpResponse = httpClient.execute(get);
                        // 如果服务器成功返回响应
                        if (httpResponse.getStatusLine().getStatusCode() == 200) {
                            // 获取服务器响应的字符串
                            return EntityUtils.toString(httpResponse
                                    .getEntity());
                        }
                        return null;
                    }
                });
        new Thread(task).start();
        return task.get();
    }
}
